package com.ruoyi.system.client.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.client.SteamDTApiClientService;
import com.ruoyi.system.domain.steamDt.BatchPlatformPriceVO;
import com.ruoyi.system.domain.steamDt.CsBaseInfoVO;
import com.ruoyi.system.domain.steamDt.CsPropResult;
import com.ruoyi.system.domain.steamDt.PlatformPriceVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Service
@Slf4j
public class SteamDTApiClientServiceImpl implements SteamDTApiClientService {
    // 请求地址
    private static final String BASE_URL = "https://open.steamdt.com/open/cs2/v1";
    // Token
//    private static final String BEARER_TOKEN = "659407343ad044348c74e1771450ff2a";
//    private static final String BEARER_TOKEN = "adca5ad0eb144c6bb81ec2898391ff0b";
    private static final String BEARER_TOKEN = "96231de71ebb4e7db73c6ec8341395f0";


    /**
     * 创建并配置HTTP连接
     */
    private HttpURLConnection createConnection(String path, String method) throws IOException {
        URL url = new URL(BASE_URL + path);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // 基础配置
        connection.setRequestMethod(method);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Authorization", "Bearer " + BEARER_TOKEN);

        // 超时设置（重要）
        connection.setConnectTimeout(30000); // 30秒连接超时
        connection.setReadTimeout(60000);    // 60秒读取超时

        connection.setDoOutput(true);

        return connection;
    }

    /**
     * 创建请求体
     */
    private String createRequestBody(String bodyName, List<String> marketHashNames) {
        JSONObject requestBodyJson = new JSONObject();
        requestBodyJson.put(bodyName, marketHashNames);
        return requestBodyJson.toString();
    }


    /**
     * 发送请求
     */
    private void sendRequest(HttpURLConnection connection, String requestBody) throws IOException {
        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = requestBody.getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
            os.flush();
        }
    }


    @Override
    public List<CsBaseInfoVO> getAllCsBaseInfoVO() {
        String response = HttpUtils.sendGet(BASE_URL + "/base", null, MediaType.APPLICATION_JSON_VALUE,
                callback -> {
                    callback.setRequestProperty("Content-Type", MediaType.APPLICATION_JSON_VALUE);
                    callback.setRequestProperty("Authorization", "Bearer " + BEARER_TOKEN);
                });
        CsPropResult<CsBaseInfoVO> csBaseInfoVOResult = JSONObject.parseObject(response.toString(),
                new TypeReference<CsPropResult<CsBaseInfoVO>>() {
                });
        if (csBaseInfoVOResult.getSuccess()) {
            return csBaseInfoVOResult.getData();
        } else {
            log.error(csBaseInfoVOResult.getErrorMsg());
            throw new RuntimeException(csBaseInfoVOResult.getErrorMsg());
        }
    }

    @Override
    public List<PlatformPriceVO> getSinglePriceByMarketHashName(String marketHashName) {
        List<PlatformPriceVO> data = new ArrayList<>();
        try {
            // 创建URL对象
            String path = "/price/single?marketHashName=" + marketHashName;
            HttpURLConnection connection = createConnection(path, "GET");

            // 读取响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            CsPropResult<PlatformPriceVO> platformPriceVO = JSONObject.parseObject(response.toString(), new TypeReference<CsPropResult<PlatformPriceVO>>() {
            });
            data = platformPriceVO.getData();
            // 关闭连接
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }

    @Override
    public List<BatchPlatformPriceVO> getBatchPriceByMarketHashNames(List<String> marketHashNames, String bearerToken) {
        // 参数校验
        if (marketHashNames == null || marketHashNames.isEmpty()) {
            return Collections.emptyList();
        }
        List<BatchPlatformPriceVO> data = new ArrayList<>();
        try {
            // 创建URL对象
            JSONObject requestBodyJson = new JSONObject();
            requestBodyJson.put("marketHashNames", marketHashNames);
            String requestBody = requestBodyJson.toString();

            URL url = new URL(BASE_URL + "/price/batch");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置请求方法

            connection.setRequestMethod("POST");
            // 设置请求头
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Authorization", "Bearer " + bearerToken);
            // 设置请求体
            connection.setDoOutput(true);
            // 写入请求体
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = requestBody.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            // 读取响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            CsPropResult<BatchPlatformPriceVO> batchPlatformPriceVO = JSONObject.parseObject(response.toString(), new TypeReference<CsPropResult<BatchPlatformPriceVO>>() {
            });
            data = batchPlatformPriceVO.getData();
            // 关闭连接
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }

    @Override
    public List<BatchPlatformPriceVO> getBatchPriceRestTemplateByMarketHashNames(List<String> marketHashNames) {
        JSONObject requestBodyJson = new JSONObject();
        requestBodyJson.put("marketHashNames", marketHashNames);
        String requestBody = requestBodyJson.toString();
        String response = HttpUtils.sendPost(BASE_URL + "/price/batch", requestBody, MediaType.APPLICATION_JSON_VALUE,
                callback -> {
                    callback.setRequestProperty("Authorization", "Bearer " + BEARER_TOKEN);
                });
        CsPropResult<BatchPlatformPriceVO> batchPlatformPriceVO = JSONObject.parseObject(response.toString(), new TypeReference<CsPropResult<BatchPlatformPriceVO>>() {
        });
        return batchPlatformPriceVO.getData();
    }


}
